package com.lagou.demo.service.impl;

import com.lagou.demo.constant.OrderStatus;
import com.lagou.demo.dao.OrderDao;
import com.lagou.demo.pojo.Order;
import com.lagou.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Autowired
    OrderDao orderDao;
    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public String placeOrder() {

        //1.模拟用户下单
        String orderId = UUID.randomUUID().toString();
        Integer orderStatus = OrderStatus.TO_BE_PAID;
        Order order = new Order();
        order.setId(orderId).setStatus(orderStatus);
        orderDao.insertOneOrder(order);
        log.info("用户下单成功，订单号为:{}，订单的状态为:{}", orderId, orderStatus);

        //2.发送一条等待付款的消息
        rabbitTemplate.convertAndSend("order_exchange", "order.biz", orderId);
        log.info("用户生成了一个待付款的订单，订单号为:{}", orderId);

        return "用户下单成功,跳转到等待付款页面";
    }

    @Override
    public String paidOrder(String orderId) {

        //1.检查订单状态，只有订单待付款才消费订单信息
        Order order = orderDao.getOrderById(orderId);
        Integer status = order.getStatus();
        if (Objects.equals(status, OrderStatus.TO_BE_PAID)) {
            String receivedOrderId = (String) rabbitTemplate.receiveAndConvert("order_queue");
            log.info("用户在规定时间内付款主动消费了一条待付款的订单消息，该订单号为:{}", receivedOrderId);

            //将订单的状态修改为已支付
            orderDao.updateOrderStatusById(receivedOrderId, OrderStatus.HAS_PAID);
            log.info("订单号为:{}的订单状态修改为已支付", receivedOrderId);
            return "跳转到付款成功页面";
        }
        return "付款失败";
    }
}
